package com.zzhrtech.wgzx_cityzen.ui.contact;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.GsonRequest;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;
import com.squareup.picasso.Picasso;
import com.zzhrtech.WgzxApplication;
import com.zzhrtech.wgzx_cityzen.Constans;
import com.zzhrtech.wgzx_cityzen.MainActivity;
import com.zzhrtech.wgzx_cityzen.R;
import com.zzhrtech.wgzx_cityzen.base.BaseFragment;
import com.zzhrtech.wgzx_cityzen.base.OnItemClickLitener;
import com.zzhrtech.wgzx_cityzen.beans.contact.ActivListBean;
import com.zzhrtech.wgzx_cityzen.beans.contact.CatListBean;
import com.zzhrtech.wgzx_cityzen.beans.contact.JifenDhBean;
import com.zzhrtech.wgzx_cityzen.beans.contact.JifenGoodsBean;
import com.zzhrtech.wgzx_cityzen.beans.disease.RoleListBean;
import com.zzhrtech.wgzx_cityzen.beans.me.LoginBean;
import com.zzhrtech.wgzx_cityzen.beans.task.BaseBean;
import com.zzhrtech.wgzx_cityzen.entity.TabEntity;
import com.zzhrtech.wgzx_cityzen.ui.me.WebviewActivity;

import org.stringtemplate.v4.STRawGroupDir;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class ContactFragment extends BaseFragment {


    private RecyclerView recy_actiy;
    private RollPagerView rollview;
    private TextView tv_dhjl,tv_points,tv_rizhi,emptyView;


    private CommonTabLayout mTabLayout;

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    private int[] mIconUnselectIds = {
            R.mipmap.ic_confuzhuang2, R.mipmap.ic_conbaihuo2,
            R.mipmap.ic_conshipin2};
    private int[] mIconSelectIds = {
            R.mipmap.ic_confuzhuang, R.mipmap.ic_conbaihuo,
            R.mipmap.ic_conshipin};
    List<CatListBean.Data> catList;
    private String catId = "",fidId = "",sort = "";
    public ContactFragment() {
        // Required empty public constructor
    }

    public static ContactFragment newInstance() {

        Bundle args = new Bundle();

        ContactFragment fragment = new ContactFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view =  inflater.inflate(R.layout.fragment_contact, container, false);
        recy_actiy = (RecyclerView) view.findViewById(R.id.recy_actiy);
        tv_dhjl = (TextView) view.findViewById(R.id.tv_dhjl);
        tv_points = (TextView) view.findViewById(R.id.tv_points);
        emptyView = (TextView) view.findViewById(R.id.emptyView);
        tv_rizhi= (TextView) view.findViewById(R.id.tv_rizhi);
        mTabLayout = (CommonTabLayout) view.findViewById(R.id.tl_3);
        rollview = (RollPagerView) view.findViewById(R.id.rollview);
        recy_actiy.setLayoutManager(new GridLayoutManager(mActivity,3));
        recy_actiy.setItemAnimator(new DefaultItemAnimator());

//        dhAdapter = new JifenDhAdapter();
//        recy_actiy.setAdapter(dhAdapter);
//
//        dhAdapter.setOnItemClickLitener(new OnItemClickLitener() {
//            @Override
//            public void onItemClick(View view, int position) {
//                if (dhAdapter.getGoodsInen(position) == 0){
//                    showToast("暂时没有该商品!");
//                }else {
//                    Intent intent = new Intent(mActivity, JifenDetailActivity.class);
//                    intent.putExtra("goodid", dhAdapter.getGoodsId(position));
//                    intent.putExtra("jifen",tv_points.getText().toString());
//                    startActivityForResult(intent,2);
//                }
//            }
//        });

        tv_dhjl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(mActivity)
                        .title("排序")
                        .items(R.array.fields)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                switch (which){
                                    case 0:
                                        fidId = "num";
                                        sort = "asc";
                                        break;
                                    case 1:
                                        fidId = "goodNum";
                                        sort = "asc";
                                        break;
                                    case 2:
                                        fidId = "goodNum";
                                        sort = "desc";
                                        break;
                                }
                                notifyList();
                            }
                        })
                        .show();
//                Intent intent = new Intent(mActivity,JifenDhActivity.class);
//                startActivity(intent);
            }
        });

        tv_rizhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity,PrizeListActivity.class);
                startActivity(intent);
            }
        });

        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                catId = catList.get(position).getCat_id();

                notifyList();
            }

            @Override
            public void onTabReselect(int position) {
            }
        });



        return view;
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser){
            httpGetInfo();
        }

    }

    @Override
    protected void initData() {
        super.initData();

        httpGetActiv();
        httpGetCatList();
    }

    private void notifyList(){
        httpGetRole();
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0){

                emptyView.setVisibility(View.GONE);
                List<JifenGoodsBean.Data> dataList = (List<JifenGoodsBean.Data>) msg.obj;
//                dhAdapter.cleanList();
//                for (JifenGoodsBean.Data data : dataList){
//                    dhAdapter.addItem(data);
//                }

            }else if (msg.what == 1){
                List<ActivListBean.Data> datas = (List<ActivListBean.Data>) msg.obj;
                rollview.setAdapter(new TestNomalAdapter(datas));

            }else if (msg.what == 2){
                catList = (List<CatListBean.Data>) msg.obj;
                for (int i = 0;i < catList.size(); i++){
                    mTabEntities.add(new TabEntity(catList.get(i).getCat_name(), mIconSelectIds[i], mIconUnselectIds[i]));
                }
                mTabLayout.setTabData(mTabEntities);

                catId = catList.get(0).getCat_id();
                notifyList();

            }else if (msg.what == 3){
                LoginBean.Data data = (LoginBean.Data) msg.obj;
                tv_points.setText(data.getNum());
            }

            return false;
        }
    });

    //获取商品列表
    private void httpGetRole(){
        Map<String,String> params = new HashMap<String, String>();
        params.put("cat_id",catId);
        params.put("field",fidId);
        params.put("sort",sort);
        GsonRequest<JifenGoodsBean> gsonRequest = new GsonRequest<JifenGoodsBean>(Request.Method.POST, Constans.HTTP_GOODSLIST, JifenGoodsBean.class, params, new com.android.volley.Response.Listener<JifenGoodsBean>() {
            @Override
            public void onResponse(JifenGoodsBean response) {

                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 0;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                }else {
                    emptyView.setVisibility(View.VISIBLE);
//                    dhAdapter.cleanList();
//                    dhAdapter.notifyDataSetChanged();
////                    showToast(response.getMsg());
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====",error + "");
                emptyView.setVisibility(View.VISIBLE);
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }

    private void httpGetActiv(){
        Map<String,String> params = new HashMap<String, String>();
        params.put("citizen_id",((MainActivity) mActivity).getCache().getAsString(Constans.keyUid));
        GsonRequest<ActivListBean> gsonRequest = new GsonRequest<ActivListBean>(Request.Method.POST, Constans.HTTP_ACTIVLIST, ActivListBean.class, params, new com.android.volley.Response.Listener<ActivListBean>() {
            @Override
            public void onResponse(ActivListBean response) {

                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 1;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                }else {
                    showToast(response.getMsg());
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====",error + "");
//                dialog.dismiss();
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }



    private void httpGetCatList(){

        GsonRequest<CatListBean> gsonRequest = new GsonRequest<CatListBean>(Request.Method.GET, Constans.HTTP_CATLIST, CatListBean.class, null, new com.android.volley.Response.Listener<CatListBean>() {
            @Override
            public void onResponse(CatListBean response) {

                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 2;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                }else {
                    showToast(response.getMsg());
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====",error + "");
//                dialog.dismiss();
            }
        });
        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }

    private void httpGetInfo(){
        Map<String,String> params = new HashMap<String, String>();
        params.put("citizen_id",((MainActivity) getActivity()).getCache().getAsString(Constans.keyUid));
        GsonRequest<LoginBean> gsonRequest = new GsonRequest<LoginBean>(com.android.volley.Request.Method.POST, Constans.HTTP_USERINFO, LoginBean.class, params, new com.android.volley.Response.Listener<LoginBean>() {
            @Override
            public void onResponse(LoginBean response) {
                if (response.isSuccess()){
                    Message message = new Message();
                    message.what = 3;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                }else {
                    showToast(response.getMsg());
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====",error + "");
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }


    private class TestNomalAdapter extends StaticPagerAdapter{

        List<ActivListBean.Data> mDatas;
        public TestNomalAdapter(List<ActivListBean.Data> datas){

            mDatas = datas;

        }
        @Override
        public View getView(ViewGroup container, final int position) {

            View view = LayoutInflater.from(mActivity).inflate(R.layout.item_rollactiv,null);

            ImageView mImageView = (ImageView) view.findViewById(R.id.image);
            TextView mNameView = (TextView) view.findViewById(R.id.name);
            TextView mTimeView = (TextView) view.findViewById(R.id.time);

            Picasso.with(mActivity).load(mDatas.get(position).getImgTh()).into(mImageView);
            mNameView.setText(mDatas.get(position).getName());
            mTimeView.setText(mDatas.get(position).getStartTime());


            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, WebviewActivity.class);
                    intent.putExtra("url",mDatas.get(position).getPlay());
                    intent.putExtra("title","抽奖");
                    startActivity(intent);
                }
            });
            return view;
        }

        @Override
        public int getCount() {
            return mDatas.size();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 2 & resultCode == Activity.RESULT_OK){
            httpGetInfo();
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}
